#include <iostream>
#include <cerrno>
#include <cstring>
#include <assert.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/ipc.h>

using namespace std;

#define PATHNAME "."
#define PROJID 0x666
#define SIZE 1024


int main()
{
    //1.创建key
    int key = ftok(PATHNAME, PROJID);
    if(key == -1)
    {
        cerr << errno << ": " << strerror(errno) << endl;
        exit(-1);
    }

    //2.创建共享内存
    umask(0);
    int shmid = shmget(key, SIZE, IPC_CREAT | IPC_EXCL | 0666);//重新设置一下权限
    if(shmid == -1)
    {
        cerr << errno << ": " << strerror(errno) << endl;
        exit(-1);
    }

    //3.建立链接
    char *start = (char*)shmat(shmid, nullptr, 0);
    
    //4.读取
    int cnt = 6;
    while(cnt--)
    {
        cout << start << endl;
        sleep(1);
    }

    //5.去关联
    int n = shmdt(start);
    assert(n != -1);
    (void)n;

    //6.删除共享内存
    int ret = shmctl(shmid, IPC_RMID, nullptr);
    assert(n != -1);
    cout << "退出" << endl;
    
    return 0;
}